<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- table -->
      <BreakSpace label="旧件销毁申请" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <BreakSpace label="上传视频/压缩文件" :containerStyle="{ marginBottom: '10px' }" />
      <Spin :spinning="loading" tip="Loading...">
        <UploadFile action-url="/api/file/oss/upload"  :fileTypes="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'rar', 'zip','mp4','avi','rmvb','WMV','ins','inr']" :fileSize="100" :isOnlyButton="true"  :limit="10000" @change="successHandler">上传附件</UploadFile>
        <FilterTable
          ref="fileTable"
          :columns="columnsFile"
          columnsRef="whbydUploadFile"
          :isSelectColumn="false"
          :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)"
          height=auto
          :dataSource="list"
        />
      </Spin>
      <BreakSpace label="旧件列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :dataSource="dataList"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onCellChange="onCellChange"
        :isSelectColumn="false"
        height="auto"
        :isPagination="false"
      >
      </FilterTable>
      <div style="padding-top: 3rem"></div>
      <BreakSpace label="操作记录" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable ref="table1" :columns="columns1" :datakey="'records'" :isSelectColumn="false" :onColumnsChange="columns => (this.columns1 = columns)" height="auto" :isPagination="false">
      </FilterTable>
      <div style="padding-top: 3rem"></div>
      <FormPanel ref="formPanel1" :list="formList1" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandleFile" />
      <div style="padding-top: 3rem"></div>
      <div
        :style="{
          position: 'fixed',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <multiuse-button type="primary" @click="back" v-show="editIds.length > 0" :disabled="index == 0">上一单</multiuse-button>
        <multiuse-button type="primary" @click="next" v-show="editIds.length > 0" :disabled="index == editIds.length - 1">下一单</multiuse-button>
        <multiuse-button type="primary" :click="carry.bind()" :disabled="editIds[index] && editIds[index].status == 1">通 过</multiuse-button>
        <multiuse-button type="primary" :click="reject1.bind()" :disabled="editIds[index] && editIds[index].status == 1">驳 回</multiuse-button>
        <multiuse-button type="primary" :click="refuse1.bind()" :disabled="editIds[index] && editIds[index].status == 1">拒 绝</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
import { approveDestory, edit } from '@/api/usedPartsDestructionFactory/UsedPartsDestructionExamine';
import { getPartType } from '@/api/dictionary';
import moment from 'moment';

export default {
  props: ['editObj', 'editIds'],
  data() {
    return {
      loading: false,
      dataList: [],
      dataList1: [],
      visible: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columns1: this.creatHeader1(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      formList1: this.createFormList1(),
      columnsFile: this.createdTable(),
      saveData: null,
      activeName: '审核记录',
      saveDataFile: {},
      visibleList: false,
      editRow: {},
      index: 0,
      statusType: null,
      number: 0,
      list: [],
    };
  },
  async created() {
    this.loading = true;
    if (this.editIds.length) {
      console.log(1);
      await this.getData(this.editIds[0]);
    } else {
      console.log(2);
      await this.getData(this.editObj);
    }
    this.loading = false;
  },
  mounted() {},
  methods: {
    async next() {
      if (this.index != this.editIds.length - 1) {
        this.index++;
      }
      this.loading = true;
      await this.getData(this.editIds[this.index]);
      this.loading = false;
    },
    async back() {
      if (this.index != 0) {
        this.index--;
        this.loading = true;
        await this.getData(this.editIds[this.index]);
        this.loading = false;
      }
    },
    async getData(row) {
      let res = await edit(row.destoryId);
      this.editRow = res.data;
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(this.editRow.fileList);
      await this.assignment();
    },
    async assignment() {
      let res0 = await getPartType({ type: 5500 });
      this.columns.find(x => x.dataIndex == 'ifReturn').editItems = res0.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      let res = await getPartType({ type: 5531 });
      for (let row in this.editRow) {
        this.formList.map(x => {
          // if (row == 'fileList' && x.fieldName == 'wayFiles') {
          //   x.initialValue = this.editRow.fileList.map(f => ({ name: f.title, url: f.fileUrl }));
          // }
          if (x.fieldName == 'destoryStatus') {
            x.initialValue = res.data.find(x => x.codeId == this.editRow.destoryStatus).codeCnDesc;
          }
          if (x.fieldName == row) {
            x.initialValue = this.editRow[row];
          }
        });
        this.formList1.map(x => {
          if (x.fieldName == row) {
            x.initialValue = this.editRow[row];
          }
        });
      }

      let list = Object.assign([], this.editRow.dtlList);
      list.map(x => {
        x.claimNo = x.cmsClaimNo;
        x.pestructionCount = x.partCount;
        x.partCount = x.claimPartCount;
        x.claimId = x.cmsClaimId;
      });
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
    },
    onCellChange(columns, row) {
      let sum = 0;
      this.$refs.table.$refs.pageTable.list.map(x => {
        console.log(x);
        sum += Number(x.pestructionCount);
      });
      this.formList.find(x => x.fieldName == 'destoryCount').initialValue = sum;
      this.formList.find(x => x.fieldName == 'cmsClaimCount').initialValue = this.$refs.table.$refs.pageTable.list.length;
    },

    add() {
      this.visibleList = true;
    },
    closeAdd() {
      this.visibleList = false;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    formChangeHandleFile(val) {
      this.saveDataFile = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    deleteHandle(row) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([row]);
    },
    //通过
    async carry() {
      this.statusType = 55311003;
      let isTable;
      isTable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
      if (isTable) {
        return;
      }
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs.formPanel1.SUBMIT_FORM();
      await this.saveDialog(this.statusType);
    },
    //驳回
    async reject1() {
      this.statusType = 55311004;
      this.formList1.find(x => x.fieldName === 'checkRemark').rules[0].required = true;
      let isTable;
      isTable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
      if (isTable) {
        return;
      }
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs.formPanel1.SUBMIT_FORM();
      if (this.saveDataFile.checkRemark === undefined || this.saveDataFile.checkRemark === null || this.saveDataFile.checkRemark === "") {
        return;
      }
      await this.saveDialog(this.statusType);
    },
    //拒绝
    async refuse1() {
      this.statusType = 55311005;
      this.formList1.find(x => x.fieldName === 'checkRemark').rules = [{ required: true, message: '请输入审核说明', trigger: 'change' }];
      // let isTable;
      // isTable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
      // if (isTable) {
      //   return;
      // }
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs.formPanel1.SUBMIT_FORM();
      console.log(this.saveDataFile.checkRemark);
      if (this.saveDataFile.checkRemark === undefined || this.saveDataFile.checkRemark === null || this.saveDataFile.checkRemark === "") {
        return;
      }
      await this.saveDialog(this.statusType);
    },
    //保存
    async saveDialog(statusType) {
      let list = this.$refs.table.$refs.pageTable.list;
      let save = Object.assign({}, this.saveData);
      list.map(x => {
        x.cmsClaimId = x.claimId;
        x.cmsClaimNo = x.claimNo;
        let partCount = x.partCount;
        x.partCount = x.pestructionCount;
        x.claimPartCount = partCount;
      });

      save.dtlList = list;

      for (let a in this.editRow) {
        if (save[a]) {
          this.editRow[a] = save[a];
        }
      }

      this.editRow.destoryStatus = statusType;

      this.editRow.checkRemark = this.saveDataFile.checkRemark;

      this.editRow.destoryDate = moment(this.saveData.destoryDate).format('YYYY-MM-DD HH:mm:ss');

      this.loading = true;
      let res = await approveDestory(this.editRow);
      if (res.resultCode == 200) {
        if (this.editIds.length) {
          this.editIds[this.index].status = 1;
          await this.next();
        } else {
          this.$emit('save');
        }
      }
      this.loading = false;
    },
    //取消操作
    closeDialog() {
      this.$emit('close');
    },
    chooseOrderNo() {
      this.visible = true;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '销毁单号',
          fieldName: 'destoryNo',
          placeholder: '',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '单据状态',
          fieldName: 'destoryStatus',
          placeholder: '',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '索赔单数量',
          fieldName: 'cmsClaimCount',
          placeholder: '',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '销毁数量',
          fieldName: 'destoryCount',
          placeholder: '',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '预计销毁日期',
          fieldName: 'destoryDate',
          placeholder: '请选择日期...',
          valueFormat: 'yyyy-MM-dd', //返回数据格式
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '操作人',
          fieldName: 'destoryBy',
          placeholder: '请输入操作人...',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '操作人电话',
          fieldName: 'destoryTel',
          placeholder: '请输入操作人电话...',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remarks',
          placeholder: '',
          rows: 3,
          selfCols: 3, // 元素占据几行
          initialValue: '',
          disabled: true
        },
        // {
        //   type: 'UPLOAD_FILE',
        //   label: '上传附件',
        //   fieldName: 'wayFiles',
        //   disabled: true, // 置灰
        //   placeholder: '上传附件...',
        //   rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
        //   initialValue: [],
        //   upload: {
        //     actionUrl: '/api/file/oss/upload',
        //     tipText: '支持PDF、RAR、JPG格式'
        //   }
        // }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '附件标题',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              <a style="color:#bb0a30" href={p.row.fileUrl} target="_blank" download={p.row.title}>
                {p.row.title}
              </a>
            );
          }
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '数量', dataIndex: 'partCount', sorter: true },
        { title: '销毁数量', dataIndex: 'pestructionCount', sorter: true },
        { title: '销毁说明', dataIndex: 'partRemarks', sorter: true },
        {
          title: '是否回运',
          dataIndex: 'ifReturn',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editRequired: true,
          editItems: []
        }
      ];
    },
    creatHeader1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '操作人', dataIndex: 'checkBy', sorter: true },
        { title: '审核时间', dataIndex: 'checkAt', sorter: true },
        { title: '审核状态', dataIndex: 'checkStatus', sorter: true },
        { title: '审核说明', dataIndex: 'checkRemarks', sorter: true }
      ];
    },
    createFormList1() {
      return [
        {
          type: 'TEXT_AREA',
          label: '审核说明',
          fieldName: 'checkRemark',
          placeholder: '审核说明',
          rules: [{ required: false, message: '请输入审核说明...', trigger: 'change' }],
          rows: 3,
          selfCols: 3, // 元素占据几行
          initialValue: ''
        }
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
